<template>
        <van-sticky>
        <van-nav-bar
            title="我的收货地址"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

    <van-address-list
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="ToAdd"
        @edit="ToEdit"
        @select="onSelected"
        v-if="action === 'order'"
    />

    <van-address-list
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="ToAdd"
        @edit="ToEdit"
        @select="onSelected"
        v-else
    />

</template>

<script setup>
const { proxy } = getCurrentInstance();

const selectedAddressId = ref(0);
const list = reactive([]);
const action = ref(proxy.$route.query.action ?? '');


// 调用生命周期
onBeforeMount(() => {
    getAddressData();
})

// 获取当前登录用户的收货地址
const getAddressData = async () => {
    let data = {
        busid:proxy.$business.value.id
    }

    let result = await proxy.$post({
        url:'business/address/index',
        params:data
    })

    if(result.code === 1)
    {
        // 把list数组清空
        list.length = 0;

        for(let item of result.data)
        {
            list.push({
                id:item.id,
                name:item.consignee,
                tel:item.mobile,
                address:item.provinces.name + item.citys.name + item.districts.name + item.address,
                isDefault:item.status == 1 ? true : false
            });

            if(item.status == 1)
            {
                selectedAddressId.value = item.id;
            }
        }

        return false;
    }else{
        proxy.$warnNotify(result.msg);

        return false;
    }
}

const onSelected = async (values) => {
    if(action.value === 'order')
    {
        proxy.$cookies.set('address',values);

        onBack();
    }else{
        let params = {
            busid:proxy.$business.value.id,
            id:values.id
        }

        let result = await proxy.$post({
            url:'/business/address/selected',
            params
        })

        if(result.code === 1)
        {
            selectedAddressId.value = values.id;

            getAddressData();

            proxy.$successNotify(result.msg);

            return false;
        }else{
            proxy.$warnNotify(result.msg);

            return false;
        }
    }
}


const ToAdd = () => proxy.$router.push('/business/address/add');

// const ToEdit = (item) => proxy.$router.push(`/business/address/edit?addrid=${item.id}`);
const ToEdit = (item) => proxy.$router.push({path:'/business/address/edit',query:{addrid:item.id}});

const onBack = () => {
    proxy.$router.back();
}
</script>